<template>
  <div class="m-chart-base">
    <div class="u-chart" ref="chartRef" :style="{ backgroundColor }"></div>
    <div v-if="hasZoom" class="u-zoom" :class="{ 'u-right': hasRight }"></div>
  </div>
</template>

<script setup name="MChartBase">
import { onMounted, ref, nextTick } from 'vue'
import * as echarts from 'echarts'
import useZoom from './useZoom'

/**
 * 基础图表，传入echarts配置即可，会与内置的默认参数进行合并。组件附加了resize逻辑。
 */
const props = defineProps({
  option: {
    type: Object,
    default() {
      return {}
    },
  },
  backgroundColor: {
    type: String,
    default: '#F5F8FC',
  },
})

const chartRef = ref()
let chartInstance = null
// 是否有区间滚动
const hasZoom = !!props.option?.dataZoom

const { hasRight, changeZoom } = useZoom({
  xDataLength: props.option?.xAxis?.data?.length,
  startValue: props.option?.dataZoom?.[0]?.startValue,
  endValue: props.option?.dataZoom?.[0]?.endValue,
})

// 渲染
function render() {
  if (props.option) {
    chartInstance = echarts.init(chartRef.value)
    chartInstance.setOption(props.option)

    if (hasZoom) {
      chartInstance.on('datazoom', function (params) {
        changeZoom(params.batch[0].start, params.batch[0].end)
      })
    }
  }
}

onMounted(() => {
  // 增加nextTick使echart获得正确的宽度
  nextTick(() => render())
})

defineExpose({
  getChartInstance() {
    return chartInstance
  },
})
</script>

<style lang="stylus" scoped>
.m-chart-base
  position relative
  height 100%
  .u-chart
    height 100%
  .u-zoom
    position absolute
    right 5px
    top 50%
    width 0
    height 0
    border 9px solid #DEE1E7
    border-left-width 0
    border-top-width 6px
    border-bottom-width 6px
    border-top-color transparent
    border-bottom-color transparent
    &.u-right
      border-left-width 9px
      border-right-width 0
</style>
